package features.advance.jdk.io.blocking;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author LIN
 * @date 2021-07-09
 */
public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8081);
        int count = 0;
        int max = Integer.MAX_VALUE;
        try{
            while(true){

                count++;
                Socket accept = serverSocket.accept();
                System.out.println("服务端有客户访问"+count);
                InputStream inputStream = accept.getInputStream();
                System.out.println("开始读取客户输入...");
                int read;
                StringBuilder sb = new StringBuilder();
                while( (read = inputStream.read())!= -1){
                    sb.append((char)read);
                }
                HashMap map = JSONObject.parseObject(sb.toString(), HashMap.class);
                Integer num = (Integer) map.get("num");

                if(max == Integer.MAX_VALUE){
                    max = num;
                }
                Object message = map.get("message");
                System.out.println(message);
                accept.close();
                if(--max <= 0){
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            serverSocket.close();
        }


    }

}
